<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--类型数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="materialTypeName" placeholder="请输入材料类型名称" clearable size="small" prefix-icon="el-icon-search"
            style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree :data="typeOptions" :props="defaultProps" :expand-on-click-node="false"
            :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current
            @node-click="handleNodeClick" />
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="材料名称" prop="materialName">
            <el-input v-model="queryParams.materialName" placeholder="请输入材料名称" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
              v-hasPermi="['basic:material:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
              v-hasPermi="['basic:material:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['basic:material:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
              v-hasPermi="['basic:material:export']">导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="materialList" @selection-change="handleSelectionChange">
          <el-table-column label="序号" align="center" type="index" />
          <el-table-column type="selection" align="center" />
          <el-table-column label="材料名称" align="center" prop="materialName" />
          <el-table-column label="规格型号" align="center" prop="specifications" />
          <el-table-column label="钢材型号" align="center" prop="steelNumber" />
          <el-table-column label="长度(m)" align="center" prop="length" />
          <el-table-column label="销售单价" align="center" prop="unitPrice" />
          <el-table-column label="税率" align="center" prop="taxRate" />
          <el-table-column v-if="false" width="1" align="center" prop="materialTypeId" />
          <el-table-column label="状态" align="center">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.status" @change="handleStatusChange(scope.row)" :active-value="1"
                :inactive-value="0"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="cener" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['basic:material:edit']">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                v-hasPermi="['basic:material:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
          @pagination="getList" />
      </el-col>
    </el-row>

    <!-- 添加或修改材料对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="10">
          <el-col :span="12" class="infoRow">
            <el-form-item label="材料名称" prop="materialName">
              <el-input v-model="form.materialName" placeholder="请输入材料名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="infoRow">
            <el-form-item label="材料分类" prop="materialTypeId">
              <el-cascader v-model="form.materialTypeId" :options="typeOptions" filterable :show-all-levels="false"
                :props="{ label: 'label', value: 'id', children: 'children' }" clearable></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="12" class="infoRow">
            <el-form-item label="助记码" prop="mnemonicCode">
              <el-input v-model="form.mnemonicCode" placeholder="请输入助记码" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="infoRow">
            <el-form-item label="品牌名称" prop="materialBrandName">
              <el-select v-model="form.materialBrandName" placeholder="请选择品牌">
                <el-option v-for="brand in brandList" :key="brand.materialBrandName" :label="brand.materialBrandName"
                  :value="brand.materialBrandName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="12" class="infoRow">
            <el-form-item label="规格型号" prop="specifications">
              <el-select v-model="form.specifications" placeholder="请选择规格型号">
                <el-option v-for="dict in dict.type.bas_specifications" :key="dict.value" :label="dict.label"
                  :value="dict.label"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="infoRow">
            <el-form-item label="钢号" prop="steelNumber">
              <el-select v-model="form.steelNumber" placeholder="请选择钢号">
                <el-option v-for="dict in dict.type.bas_steel_number" :key="dict.value" :label="dict.label"
                  :value="dict.label"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        

        <el-row :gutter="10">
          <el-col :span="12" class="infoRow">
            <el-form-item label="长度(m)" prop="length">
              <el-input v-model="form.length" placeholder="请输入长度" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="infoRow">
            <el-form-item label="高度(m)" prop="high">
              <el-input v-model="form.high" placeholder="请输入高度" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="12" class="infoRow">
            <el-form-item label="宽度(m)" prop="width">
              <el-input v-model="form.width" placeholder="请输入宽度" />
            </el-form-item>
          </el-col>
          <el-col :span="12"  class="infoRow">
            <el-form-item label="体积(m³)" prop="volume">
              <el-input v-model="form.volume" :disabled="true" placeholder="请输入长宽高" />
            </el-form-item>
          </el-col>
        </el-row>

        

        <el-row :gutter="10">
          <el-col :span="12" class="infoRow">
            <el-form-item label="重量(t)" prop="weight">
              <el-input v-model="form.weight" placeholder="请输入重量" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="infoRow">
            <el-form-item label="单价(/t)" prop="unitPrice">
              <el-input v-model="form.unitPrice" placeholder="请输入销售单价" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="12" class="infoRow">
            <el-form-item label="税率" prop="taxRate">
              <el-input v-model="form.taxRate" placeholder="请输入税率" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="infoRow">
            <el-form-item label="启用状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择启用状态">
                <el-option v-for="dict in dict.type.bas_status" :key="dict.label" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMaterial, getMaterial, delMaterial, addMaterial, updateMaterial, changeMaterialStatus, typeTreeSelect, listBrand } from "@/api/basic/material";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";


export default {
  name: "Material",
  dicts: ['bas_specifications', 'bas_steel_number', 'bas_steel_grade', 'bas_status'],
  components: {
    Treeselect
  },
  data() {
    return {
      selectedId: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 材料表格数据
      materialList: [],
      brandList: [],
      materialTypeName: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 是否展开，默认全部展开
      isExpandAll: false,
      // 材料类型树选项
      typeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materialTypeId: null,
        materialName: null,
        materialTypeName: null
      },
      // quertParams:{}
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label",
        value: "id"
      },
      // 表单校验
      rules: {
        materialName: [
          { required: true, message: "材料名称不能为空", trigger: "blur" }
        ],
        specifications: [
          { required: true, message: "规格型号不能为空", trigger: "change" }
        ],
        taxRate: [
          { required: true, message: "税率不能为空", trigger: "blur" }
        ],
        length: [
          { required: true, message: "长度不能为空", trigger: "blur" }
        ],
        materialTypeId: [
          { required: true, message: "材料类型不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ],
        unitPrice: [
          { required: true, message: "单价不能为空", trigger: "blur" }
        ],
        steelNumber: [
          { required: true, message: "钢号不能为空", trigger: "blur" }
        ],
        weight: [
          { required: true, message: "重量不能为空", trigger: "blur" }
        ],
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    materialTypeName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询材料列表 */
    getList() {
      this.loading = true;
      listMaterial(this.queryParams).then(response => {
        this.materialList = response.rows;
        this.total = response.total;
        this.loading = false;
        // console.log(this.materialList, "materialList")
      });
      typeTreeSelect().then(response => {
        this.typeOptions = response.data;
        console.log(this.typeOptions, "typeOptions")

      })
      listBrand(this.queryParams).then(response => {
        this.brandList = response.rows;
      });
      
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      // console.log(data, "data")
      this.queryParams.materialTypeId = data.id;
      this.handleQuery();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        materialId: null,
        materialName: null,
        mnemonicCode: null,
        // financialCode: null,
        materialTypeId: null,
        materialBrandName: null,
        // grade: null,
        length: null,
        high: null,
        width: null,
        volume: null,
        // commissionPrice: null,
        specifications: null,
        steelNumber: null,
        // unit: null,
        weight: null,
        unitPrice: null,
        taxRate: null,
      };
      this.resetForm("form");
    },

    // 材料状态修改
    handleStatusChange(row) {
      let text = row.status === 1 ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.materialName + '"材料吗？').then(function () {
        return changeMaterialStatus(row.materialId, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.status = row.status === 0 ? 1 : 0;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.materialId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加材料";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const materialId = row.materialId || this.ids
      getMaterial(materialId).then(response => {
        response.data.status = response.data.status + ""
        this.form = response.data;
        this.open = true;
        this.title = "修改材料";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // console.log(this.form, "form")
          if (this.form.materialId != null) {
            if (this.form.materialTypeId && this.form.materialTypeId.length > 1) {
              this.form.materialTypeId = parseInt(this.form.materialTypeId[this.form.materialTypeId.length - 1]);
            }
            updateMaterial(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            if (this.form.materialTypeId && this.form.materialTypeId.length > 1) {
              this.form.materialTypeId = parseInt(this.form.materialTypeId[this.form.materialTypeId.length - 1]);
            }
            addMaterial(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const materialIds = row.materialId || this.ids;
      this.$modal.confirm('是否确认删除材料编号为"' + materialIds + '"的数据项？').then(function () {
        return delMaterial(materialIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('basic/material/export', {
        ...this.queryParams
      }, `material_${new Date().getTime()}.xlsx`)
    }
  },
  computed: {
    calculateVolume() {
      let length = parseFloat(this.form.length);
      let high = parseFloat(this.form.high);
      let width = parseFloat(this.form.width);

      if (isNaN(length) || isNaN(high) || isNaN(width)) {
        return '';
      }

      return (length * high * width).toFixed(2);
    }
  },
  watch: {
    calculateVolume(newVolume) {
      this.form.volume = newVolume;
    }
  }
};
</script>
<style>
.infoRow {
  margin-bottom: 10px;
}
</style>
